import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/models/report/basketsResult.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/dialogs/basketGradeDialog.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

// ignore: must_be_immutable
class BasketDataGrid extends StatelessWidget {
  BasketDataGrid({Key? key, required this.basketItems}) : super(key: key);

  final box = Hive.box('appconfig');
  List<BasketItem> basketItems;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];
  DataGridController _dataGridController = DataGridController();
  ReportsController _reportsController = Get.find();
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build BasketDataGrid');
    return Expanded(child: _buildDataGrid());
  }

  Container _buildDataGrid() {
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;

    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source:
              BasketDataGridSource(items: basketItems, isTeacher: isTeacher),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          showCheckboxColumn: false,
          allowSorting: true,
          allowTriStateSorting: true,
          allowFiltering: true,
          allowSwiping: isTeacher,
          controller: _dataGridController,
          selectionMode: isTeacher ? SelectionMode.none : SelectionMode.single,
          navigationMode: GridNavigationMode.row,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            if (isTeacher) {
              var classId = box.get(CacheManagerKey['currentclass'].toString());
              return GestureDetector(
                  onTap: () {
                    var id = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    _reportsController
                        .removeFromBasket(classId, id)
                        .then((statusMessage) {
                      if (statusMessage.status == 1000) {
                        Future.delayed(Duration(milliseconds: 1200), (() {
                          Get.snackbar('Message'.tr, 'Successfully deleted'.tr,
                              backgroundColor: Theme.of(context).primaryColor,
                              colorText: Theme.of(context).primaryColorLight,
                              snackPosition: SnackPosition.BOTTOM);
                        }));
                      } else {
                        Future.delayed(Duration(milliseconds: 1200), (() {
                          Get.snackbar('Message'.tr,
                              'Failed to delete, please try again later.'.tr,
                              backgroundColor: Theme.of(context).primaryColor,
                              colorText: Theme.of(context).primaryColorLight,
                              snackPosition: SnackPosition.BOTTOM);
                        }));
                      }
                    });
                  },
                  child: Container(
                      color: Colors.redAccent,
                      child: Center(
                        child: Icon(Icons.delete),
                      )));
            } else {
              return null;
            }
          },
          columns: <GridColumn>[
            GridColumn(
              width: 180,
              visible: isTeacher,
              columnName: 'FirstName',
              label: buildDataGridColumnLabel('FirstName'),
            ),
            GridColumn(
              width: 180,
              columnName: 'LastName',
              visible: isTeacher,
              label: buildDataGridColumnLabel('LastName'),
            ),
            GridColumn(
              width: isWebOrDesktop ? 210.0 : 160.0,
              columnName: 'Task',
              allowFiltering: false,
              label: buildDataGridColumnLabel('Task'),
            ),
            GridColumn(
              columnName: 'Book',
              width: isWebOrDesktop ? 260.0 : 180.0,
              label: buildDataGridColumnLabel('Book Title'),
            ),
            GridColumn(
              columnName: 'Type',
              //allowFiltering: false,
              width: isWebOrDesktop ? 160.0 : 130.0,
              label: buildDataGridColumnLabel('Type'),
            ),
            GridColumn(
              columnName: 'Status',
              //allowFiltering: false,
              width: isWebOrDesktop ? 160 : 150,
              label: buildDataGridColumnLabel('Status'),
            ),
            GridColumn(
              columnName: 'Score',
              allowFiltering: false,
              width: 150,
              label: buildDataGridColumnLabel('Score'),
            ),
            GridColumn(
              columnName: 'SubmitDate',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('SubmitDate'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
            GridColumn(
              columnName: 'all',
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('all'),
            ),
          ],
        ),
      ),
    );
  }
}

class BasketDataGridSource extends DataGridSource {
  final box = Hive.box('appconfig');

  BasketDataGridSource({required List<BasketItem> items, required isTeacher}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'FirstName',
                  value: dataGridRow.player != null
                      ? dataGridRow.player?.firstName
                      : ''),
              DataGridCell<String>(
                  columnName: 'LastName',
                  value: dataGridRow.player != null
                      ? dataGridRow.player?.lastName
                      : ''),
              DataGridCell<String>(
                  columnName: 'Task', value: dataGridRow.assignmentName),
              DataGridCell<String>(
                  columnName: 'Book', value: dataGridRow.bookTitle),
              DataGridCell<String>(
                  columnName: 'Type', value: dataGridRow.contentType),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status?.toUpperCase() ?? ''),
              DataGridCell<String>(
                  columnName: 'Score', value: dataGridRow.content?.grade ?? ''),
              DataGridCell<int>(
                columnName: 'SubmitDate',
                value: dataGridRow.when ?? 0,
              ),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
              DataGridCell<BasketItem>(columnName: 'all', value: dataGridRow)
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'SubmitDate') {
            if (dataGridCell.value > 0) {
              return Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  child: Text(
                '',
                overflow: TextOverflow.fade,
                style: Get.textTheme.bodySmall,
              ));
            }
          } else if (dataGridCell.columnName == 'Status') {
            return Container(
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                alignment: Alignment.centerLeft,
                child: GestureDetector(
                    onTap: () {
                      if (isTeacher) {
                        var item = row
                            .getCells()
                            .where((element) => element.columnName == 'all')
                            .first
                            .value;
                        showGeneralDialog(
                            context: Get.context!,
                            transitionDuration: Duration(milliseconds: 0),
                            pageBuilder: (bc, ania, anis) {
                              return BasketGrade(
                                basketItem: item,
                              );
                            });
                      } else {
                        var item = row
                            .getCells()
                            .where((element) => element.columnName == 'all')
                            .first
                            .value;
                        if (dataGridCell.value.toString() == 'GRADED') {
                          showGeneralDialog(
                              context: Get.context!,
                              transitionDuration: Duration(milliseconds: 0),
                              pageBuilder: (bc, ania, anis) {
                                return BasketGrade(
                                  basketItem: item,
                                );
                              });
                        }
                      }
                    },
                    child: Text(dataGridCell.value.toString(),
                        softWrap: true,
                        overflow: TextOverflow.fade,
                        style: Get.textTheme.titleLarge
                        //: Get.textTheme.bodySmall,
                        )));
          } else if (dataGridCell.columnName == 'FirstName') {
            return Container(
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                alignment: Alignment.centerLeft,
                child: GestureDetector(
                    onTap: () {
                      if (isTeacher) {
                        var item = row
                            .getCells()
                            .where((element) => element.columnName == 'all')
                            .first
                            .value as BasketItem;
                        var _userName = item.player?.userName ?? '';

                        Navigator.pushNamed(
                            Get.context!, '/reports/studentPersonal',
                            arguments: [item.classId, _userName]);
                      }
                    },
                    child: Text(
                      dataGridCell.value.toString(),
                      softWrap: true,
                      overflow: TextOverflow.fade,
                      style: Get.textTheme.titleLarge,
                    )));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
